const app = getApp();
import requestApi from '../../common/requestApi.js'
const urls = app.globalData.requestUrl;
Page({
  data: {
    item_info: {
      name: '向日葵之歌-向日葵三枝,戴安娜粉玫瑰三枝',
      price: 198.00,
      imgs: ['../../images/it1.jpg', '../../images/it2.jpg', '../../images/it3.jpg', '../../images/it4.jpg', ]
    },
    normal_img: [
      'https://666c-flower-271fb6-1257999444.tcb.qcloud.la/icons/del1.jpg', 'https://666c-flower-271fb6-1257999444.tcb.qcloud.la/icons/del2.jpg', 'https://666c-flower-271fb6-1257999444.tcb.qcloud.la/icons/del3.jpg', 'https://666c-flower-271fb6-1257999444.tcb.qcloud.la/icons/del4.jpg', 'https://666c-flower-271fb6-1257999444.tcb.qcloud.la/icons/del5.jpg',
    ],
    animationData: {},
    send_time: ['上午(8:00-12:00)', '下午(12:00-18:00)', '晚上(18:00-21:00)', '节日不定时配送', ],
    flag: true,
    num: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var id = options.id;
    console.log(id);
    this.getItemDetail(id);
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })

    this.animation = animation

    this.getHotItem();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var date = new Date();
    var yy = date.getFullYear();
    var mm = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1);
    var dd = date.getDate() > 9 ? date.getDate() : '0' + date.getDate();
    var start_date = yy + '-' + mm + '-' + dd;
    var end_date = (yy + 1) + '-' + mm + '-' + dd;
    this.setData({
      start_date: start_date,
      end_date: end_date
    })
  },
  showModel(e) {
    console.log(e)
    let types = e.currentTarget.dataset.types;
    this.setData({
      flag: false,
      types: types
    })
    this.animation.height(400).opacity(1).step()
    this.setData({
      animationData: this.animation.export(),
    })
    setTimeout(function() {

    }.bind(this), 500)
  },
  hideModel() {
    this.animation.height(300).opacity(0).step()

    this.setData({
      animationData: this.animation.export(),
    })
    setTimeout(function() {
      this.setData({
        flag: true
      })
    }.bind(this), 500)
  },
  getSendTime(e) {
    console.log(e)
    var idx = e.currentTarget.dataset.idx;
    var time = this.data.send_time;
    this.setData({
      sid: idx,
      time: time[idx]
    })
  },
  formSubmit(e) {
    console.log(e);
    var val = e.detail.value;
    var types = this.data.types;
    for (let i in val) {
      if (i == 'send_time' && !val[i]) {
        wx.showToast({
          title: '请选择配送时间',
        })
        return false;
      } else if (i == 'send_date' && !val[i]) {
        wx.showToast({
          title: '请选择配送日期',
        })
        return false;
      } else if (i == 'send_telephone' && !val[i]) {
        wx.showToast({
          title: '请填写电话',
        })
        return false;
      } else if (i == 'send_card' && !val[i]) {
        wx.showToast({
          title: '请填写卡片',
        })
        return false;
      }
    }
    console.log('表单验证通过!');
    this.setData({
      val: val
    })
    if (types == 'cart') {
      this.addCartList()
    } else if (types == 'buy') {
      this.addOrderList();
    }
  },
  //添加购物车
  addCartList() {
    let _this = this;
    let db = wx.cloud.database();
    let val = this.data.val;
    let item = this.data.item_info;
    let data = {
      cart_item_name: item.goods_name,
      cart_item_price: item.goods_price,
      cart_item_imgurl: item.imgurls,
      cart_item_id: item._id,
      cart_send_time: val.send_time,
      cart_send_date: val.send_date,
      cart_buy_number: val.send_num,
      cart_buy_telephone: val.send_telephone,
      cart_card_info: val.send_card,
      cart_leave_message: val.send_remark ? val.send_remark : '',
      cart_is_select: true
    }
    db.collection('tb_cart_list').add({
      data: data,
      success: res => {
        console.log(res)
        wx.showToast({
          title: '添加购物车成功',
        })
      },
      fail: err => {
        console.log(err)
      }
    })

  },

  addOrderList() {
    let _this = this;
    let db = wx.cloud.database();
    let val = this.data.val;
    let item = this.data.item_info;
    let arr = [];
    let data = {
      cart_item_name: item.goods_name,
      cart_item_price: item.goods_price,
      cart_item_imgurl: item.imgurls,
      cart_item_id: item._id,
      cart_send_time: val.send_time,
      cart_send_date: val.send_date,
      cart_buy_number: val.send_num,
      cart_buy_telephone: val.send_telephone,
      cart_card_info: val.send_card,
      cart_leave_message: val.send_remark ? val.send_remark : '',
      cart_is_select: true,
    }
    arr.push(data);
    wx.setStorageSync('buyinfo', arr);
    wx.navigateTo({
      url: '../payment/payment',
    })
  },
  getSubNum() {
    let num = this.data.num;
    if (num > 1) {
      num--;
    } else {
      num = 1;
    }
    this.setData({
      num: num
    })
  },
  getAddNum() {
    let num = this.data.num;
    num++;
    this.setData({
      num: num
    })
  },
  getInputNum(e) {
    let num = e.detail.value;
    console.log(e);
    if (num) {
      this.setData({
        num: num
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  getItemDetail(id) {
    let _this = this;
    let db = wx.cloud.database();
    db.collection('tb_item_list').doc(id).get({
      success: res => {
        console.log(res)
        _this.setData({
          item_info: res.data
        })
        this.judgeUserCollect();
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  //判断是否收藏
  judgeUserCollect() {
    let _this = this;
    let minfo = this.data.item_info;
    let db = wx.cloud.database();
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        let openid = res.result.openid;
        let item_id = minfo._id;
        db.collection('tb_collect_list').where({
          _openid: openid,
          item_id: item_id
        }).get({
          success: res => {
            console.log(res)
            if (res.data.length > 0) {
              _this.setData({
                is_collect: true
              })
            } else {
              _this.setData({
                is_collect: false
              })
            }
          },
          fail: err => {

          }
        });
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  getHotItem() {
    let url = urls + 'goods/findGoods',
      method = 'POST',
      data = {},
      _this = this;
    requestApi.api(url, method, data)
      .then(res => {
        console.log(res)
        _this.setData({
          item_info: res.data.data[0]
        })
      })
      .catch(err => {
        console.log(err)
      });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },
  //查找用户是否已经收藏

  //去首页
  goHome() {
    wx.switchTab({
      url: '../index/index',
    })
  },
  //查看购物车
  goCart() {
    wx.switchTab({
      url: '../cart/cart',
    })
  },
  //收藏
  goCollect() {
    if (this.data.is_collect) {
      return wx.showToast({
        title: '已经收藏了',
      })
    }
    console.log(1111111111)
    let minfo = this.data.item_info;
    let _this = this;
    let db = wx.cloud.database();
    let data = {};
    for (let i in minfo) {
      if (i == '_id') {
        data.item_id = minfo[i]
      } else if (i == '_openid') {
        data.user_openid = minfo[i]
      } else {
        data[i] = minfo[i]
      }
    }
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        console.log(res);
        let openid = res.result.openid;
        let item_id = minfo._id;
        wx.cloud.callFunction({
          name: 'getCollectList',
          data: {
            openid: openid,
            item_id: item_id
          },
          success: res => {
            console.log('有木有收藏', res);
            if (res.result.data.length > 0) {
              wx.showToast({
                title: '已经收藏了',
              })
            } else {
              console.log(data)
              db.collection('tb_collect_list').add({
                data: data,
                success: resp => {
                  console.log(resp)
                  wx.showToast({
                    title: '收藏成功',
                  })
                  _this.judgeUserCollect();
                },
                fail: errp => {
                  console.log(errp);
                  wx.showToast({
                    title: '网络错误',
                  })
                }
              })
            }
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })

  },
  bindDateChange(e) {
    console.log(e)
    this.setData({
      date: e.detail.value
    })

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})